/**
 * 维护"通知"联系人
 */
import { truthy } from '@gnlab/utils'
import { API } from '@/services/common/api'
import { type ChatRecord } from '@/services/contact-chat'
import type { BaseContact } from '@/services/contacts'
import { detectIsNotice, makeContactId, ContactType } from '@/services/contacts'
import type { LoadInfoConditions } from './common/ContactTypeService'
import { ContactTypeService } from './common/ContactTypeService'

export interface NoticeContact extends BaseContact {
  type: ContactType.notice
}

/**
 * 提供基本信息，生成一个应用通知联系人
 */
function makeNoticeContact(info: {
  ownerWxid: string
  conversationId: string
  name: string
  contacted: number
  latestChat?: ChatRecord
}): NoticeContact {
  const { ownerWxid, conversationId, name, contacted, latestChat } = info
  return {
    avatar: '',
    contacted,
    conversationId,
    id: makeContactId(ownerWxid, conversationId),
    name,
    ownerWxid,
    remark: '',
    type: ContactType.notice,
    userId: conversationId,
    initialUnread: 0,
    initialWarn: null,
    latestChat,
  }
}

/**
 * 获取应用通知列表
 */
interface RawNoticeContact {
  ConversationId: string
  SenderName: string
  Timestamp: number
  WxId: string
}
function formatRawNoticeContact(raw: RawNoticeContact): NoticeContact {
  const {
    WxId: ownerWxid,
    SenderName: name,
    ConversationId: conversationId,
    Timestamp: contacted,
  } = raw
  return makeNoticeContact({ ownerWxid, conversationId, name, contacted })
}
async function getNotices(wxids: string[]) {
  return API('/ChatHistory/GetWxApps', {
    data: { wxids },
    formatter: (raw: RawNoticeContact[]) => raw.map(formatRawNoticeContact),
  })
}

export class Notices extends ContactTypeService<NoticeContact> {
  constructor() {
    super('notices')
  }

  // 通知是一次性加载完的
  get pageSize() {
    return 100000
  }

  async request({ wxids }: { wxids: string[] }) {
    return getNotices(wxids)
  }

  tryLoadInfo({ ownerWxid, contactUserId, name, byChatRecord }: LoadInfoConditions) {
    if (detectIsNotice(contactUserId)) {
      if (truthy(name)) {
        const contact = makeNoticeContact({
          ownerWxid,
          conversationId: contactUserId,
          name,
          contacted: byChatRecord ? byChatRecord.timestamp : Date.now(),
          latestChat: byChatRecord,
        })
        this.listAddOrUpdate(contact)
        return true
      } else {
        this.logger.warn('暂不支持加载“应用通知”类联系人的信息')
        return false
      }
    }
    return null
  }
}
